all files / Services/ sort-order.service.ts

87.88% Statements 29/33
50% Branches 2/4
86.67% Functions 13/15
85.19% Lines 23/27
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66                   20× 20×                   10×         10×                 20×                          
import { Injectable } from '@angular/core';
 
import { CollectionHelper } from './collection-helper.service';
 
import { SortOrder } from 'ivy.angular.data';
 
@Injectable()
export class SortOrderService {
 
    constructor(
        private collSvc: CollectionHelper) {
    }
 
    sortCollection<T extends SortOrder>(items: T[]): void {
 
        items = items.sort((obj1: T, obj2: T) => {
            Eif (obj1.sortOrder > obj2.sortOrder) {
                return 1;
            } else {
                return -1;
            }
        });
 
    }
 
    getPreviousItem<T extends SortOrder>(items: T[], current: T): T {
 
        return this.internalGetPrevious<T, T>(items, current,
            () => null,
            targetSort => this.collSvc.firstOrDefault(items.filter(x => x.sortOrder == targetSort)));
    }
 
    getPreviousItems<T extends SortOrder>(items: T[], current: T): T[] {
 
        return this.internalGetPrevious<T, T[]>(items, current,
            () => [],
            targetSort => items.filter(x => x.sortOrder <= targetSort));
    }
 
    private internalGetPrevious<TItem extends SortOrder, TReturn>(items: TItem[], current: TItem,
        noMapsReturn: () => TReturn, mapReturn: (targetSort: number) => TReturn): TReturn {
 
        // Don't decrement, leave as less than (<) instead of less than equal to (<=)
        let targetOrder = current.sortOrder;
 
        // We have no guarantee that SortOrder will be in order properly
        // We should set this up to ensure we don't have to worry about bad configs
        let orderMaps = items.map(x => x.sortOrder).filter(x => x < targetOrder);
 
        let targetSort: number;
 
        Iif (orderMaps.length == 0) {
 
            return noMapsReturn();
 
        } else {
 
            // To get the second lowest sort order, we must get all sorts,
            // filter to sorts below the order of the current item,
            // take the max of that given collection of sorts below current
            targetSort = this.collSvc.max(orderMaps);
 
            return mapReturn(targetSort);
        }
    }
}